import {Image, View, Text, Swiper, SwiperItem} from '@tarojs/components';
import React, {Component} from 'react';
import {AtIcon, AtModal, AtModalHeader, AtModalContent, AtModalAction} from 'taro-ui';
import 'taro-ui/dist/style/components/modal.scss';
import 'taro-ui/dist/style/components/icon.scss';
import Taro, {getCurrentInstance} from '@tarojs/taro';
import {connect} from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import api from 'api';
import noticeImg from '@/assets/image/communityService/notice.png';
import ryutil from '../../../libs/ryutil';
import bg from '@/assets/image/daoway/bg.png';
import btn from '@/assets/image/daoway/btn.png';
import {ant} from 'wmkit';
actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      channel: 'rykj',
      secret: '9a5cf90547b3475b961f6f136f97659e',
      daowayUrl: '',
      modelContent: '您不是会员，无法使用该服务，需开通会员！',
      navBarHeight: 0,
      navBarPadding: 0,
      banner: [
        {
          src: require('@/assets/image/communityService/banner.png'),
        },
        {
          src: require('@/assets/image/communityService/banner.png'),
        },
      ],
    };
  }

  componentDidMount() {
    // /pages/package-D/serviceCentre/index
    let params = Taro.getCurrentInstance()?.router.params;
    this.getNavHeight();
    this.props.actions.init(params.memberType);
  }

  componentDidShow() {}

  getNavHeight() {
    const menuButtonObject = Taro.getMenuButtonBoundingClientRect();
    let menuBottonHeight = menuButtonObject.height;
    let navBarPadding = menuButtonObject.top;
    let navBarHeight = menuBottonHeight + navBarPadding;
    // const navBarPaddingR = (sysinfo.windowWidth - (menuButtonObject.right - menuButtonObject.width)) * 2
    this.setState({
      navBarHeight,
      navBarPadding: navBarPadding,
      // navBarPaddingR,
    });
  }

  async itemClick(item) {
    let {
      main: {isAquamarineMember, isCrystalMember},
      actions: {action},
    } = this.props;

    // isAquamarineMember && isCrystalMember; //双会员
    // isAquamarineMember && !isCrystalMember; //蓝晶会员
    // !isAquamarineMember && isCrystalMember; //赤晶会员
    // !isAquamarineMember && !isCrystalMember; //普通用户
    let memberType: number | null = null;
    if (isAquamarineMember && isCrystalMember) {
      //双会员
      memberType = 2;
    } else if (isAquamarineMember && !isCrystalMember) {
      //蓝晶会员
      memberType = 0;
    } else if (!isAquamarineMember && isCrystalMember) {
      //赤晶会员
      memberType = 1;
    }
    // isAquamarineMember && isCrystalMember; //双会员
    // isAquamarineMember && !isCrystalMember; //蓝晶会员
    // !isAquamarineMember && isCrystalMember; //赤晶会员
    // !isAquamarineMember && !isCrystalMember; //普通用户
    if (item.memberType !== memberType && item.memberType === 0 && item.memberType < memberType) {
      this.setState({
        modelContent: '您不是蓝晶会员，无法使用该服务，需开通会员！',
      });
      action.commonChange('main.showModel', true);
      return;
    }
    if (item.memberType !== memberType && item.memberType === 1 && item.memberType < memberType) {
      this.setState({
        modelContent: '您不是赤晶会员，无法使用该服务，需开通会员！',
      });
      action.commonChange('main.showModel', true);
      return;
    }
    if (!isAquamarineMember && !isCrystalMember) {
      action.commonChange('main.showModel', true);
    } else {
      // skipWay:0内部，1外部
      if (item.skipWay == 0) {
        Taro.navigateTo({
          url: item.url,
        });
      } else {
        if (item.outSkipWay == 0) {
          let {channel, secret} = this.state;
          let userInfos = Taro.getStorageSync('b2b-wechat@login').user || {};
          let phone = userInfos.phone;
          const param = `channel=${channel}&phone=${phone}&secret=${secret}`;
          let sign = ryutil.encrypt(param);
          const newUrl = `${item.url}&channel=${channel}&phone=${phone}&sign=${sign}&nav=0&top=1&banner=0`;
          this.setState({
            daowayUrl: newUrl,
          });
          // Taro.setStorageSync('url', newUrl);
          // Taro.navigateTo({
          //   url: '/pages/package-A/webview/index',
          // });
        } else if (item.outSkipWay == 1) {
          // 小程序跳转
          if (item.miniProgramPath == 'wxde8ac0a21135c07d') {
            //美团
            if (item.url.indexOf('-') != -1) {
              let arr = item.url.split('-');
              Taro.navigateTo({
                url: `/pages/package-D/meituan/index?cat0Id=${arr[0]}&cat1Id=${arr[1]}`,
              });
            } else {
              Taro.showToast({
                title: '菜单配置错误，请联系管理员',
                icon: 'none',
                duration: 2000,
              });
            }
          } else if (item.miniProgramPath == 'wxf772255062165d94') {
            Taro.navigateToMiniProgram({
              appId: item.miniProgramPath,
              path: item.url,
              //develop开发版；trial体验版；release正式版
              envVersion: 'release',
              success(res) {
                // 打开成功
              },
              fail(err) {},
            });
          }
        } else if (item.outSkipWay == 2) {
          // 插件跳转
          let {customerId} = this.props.main;
          let query = {
            movieuid: customerId,
            movieapikey: await ant.getAntApiKey(),
            index: '/pages/index/index',
          };
          let kvarr = [];
          for (const key in query) {
            if (Object.prototype.hasOwnProperty.call(query, key)) {
              const e = query[key];
              kvarr.push(`${key}=${e}`);
            }
          }
          let url = `plugin://${item.pluginName}/index?${kvarr.join('&')}`;

          Taro.navigateTo({
            url,
          });
        }
      }
    }
  }

  render() {
    let {banner, daowayUrl} = this.state;
    const {
      actions: {action},
      main: {showModel, list, selected},
    } = this.props;

    return (
      <View className="packageDServiceCentre">
        <View className="header-bg">
          <View
            style={{
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
              paddingTop: `${this.state.navBarPadding}px`,
              height: `${this.state.navBarHeight}px`,
            }}
          >
            <AtIcon
              onClick={() => {
                Taro.navigateBack();
              }}
              customStyle={{zIndex: 2}}
              value="chevron-left"
              size="30"
              color="#000"
            ></AtIcon>
          </View>
        </View>
        <Swiper
          key={1}
          className="imgSlides"
          autoplay //是否自动播放
          indicatorDots //是否显示面板指示点
          style={process.env.TARO_ENV === 'h5' && {height: 'auto'}}
        >
          <View />
          {banner.map((v, k) => {
            return (
              <SwiperItem key={k}>
                <Image src={v.src} className="banner" mode="widthFix" />
              </SwiperItem>
            );
          })}
        </Swiper>
        <View className="main">
          <View className="lList">
            <View className="list">
              {list.map((item, index) => (
                <View
                  className="item"
                  style={selected === index ? 'background:rgba(240, 240, 240, 0.6)' : null}
                  onClick={(e) => {
                    action.commonChange('main.selected', index);
                  }}
                >
                  <View className="f28">{item?.oneName}</View>
                  {item?.oneImageSign && (
                    <View>
                      <Image className="iconImg" src={item?.oneImageSign} mode="aspectFill" />
                    </View>
                  )}
                </View>
              ))}
            </View>
          </View>

          <View className="cList">
            {list[selected]?.twoCategoryVOList && list[selected]?.twoCategoryVOList.length && (
              <View className="list">
                {list[selected]?.twoCategoryVOList.map((item, index) => (
                  <View className="item">
                    <View
                      className="f28"
                      onClick={(e) => {
                        e.stopPropagation();
                        this.itemClick(item);
                      }}
                    >
                      {item.twoName}
                    </View>
                    <View className="f20">{item.twoSlogan}</View>
                  </View>
                ))}
              </View>
            )}
          </View>
          <View className="rList">
            {list[selected]?.oneSlogan && <View className="f20">{list[selected]?.oneSlogan}</View>}
            <View className="imgList">
              {list[selected]?.oneBrandLogo &&
                list[selected]?.oneBrandLogo.length > 0 &&
                list[selected]?.oneBrandLogo.map((item, index) => (
                  <Image className="iconImg" src={item} mode="aspectFill" />
                ))}
            </View>
          </View>
        </View>
        <AtModal
          isOpened={showModel}
          cancelText="取消"
          confirmText="开通"
          onClose={() => {
            action.commonChange('main.showModel', false);
          }}
          onCancel={() => {
            action.commonChange('main.showModel', false);
          }}
          onConfirm={() => {
            action.commonChange('main.showModel', false);
            Taro.navigateTo({url: '/pages/package-A/memberOpen/index'});
          }}
          content={this.state.modelContent}
        />
        {daowayUrl && (
          <View className="tipBox">
            <View className="tipBox-con">
              <Image className="tipBox-con-bg" src={bg} mode="aspectFit" />
              <Image
                className="tipBox-con-btn"
                src={btn}
                mode="aspectFit"
                onClick={() => {
                  Taro.setClipboardData({
                    //设置系统剪贴板的内容
                    data: daowayUrl,
                    success(res) {
                      // Taro.getClipboardData({ // 获取系统剪贴板的内容
                      //   success(res) {
                      Taro.showToast({
                        title: '内容已复制',
                      });
                      //   }
                      // })
                    },
                  });
                }}
              />
              <View
                className="tipBox-con-cancel"
                onClick={() => {
                  this.setState({
                    daowayUrl: '',
                  });
                }}
              >
                取消
              </View>
            </View>
          </View>
        )}
      </View>
    );
  }
}
